package game.module.dabt.logic;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.ItemConstants;
import game.entity.PlayingRole;
import game.module.dabt.bean.DabtBean;
import game.module.dabt.dao.DabtCache;
import game.module.dabt.dao.DabtdbDao;
import game.module.item.logic.ItemManager;
import game.module.mail.logic.MailManager;
import game.module.user.bean.PlayerBean;
import game.module.user.dao.PlayerDao;

import game.session.SessionManager;

/**
 * @author llc
 *
 */
public class Calculator {

	private static Logger logger = LoggerFactory.getLogger(Calculator.class);

	static class SingletonHolder {
		static Calculator instance = new Calculator();
	}

	public static Calculator getInstance() {
		return SingletonHolder.instance;
	}

	public void test() {
		int so[] = new int[] { -100, 20, 60, 20 };
		List<Integer> play = new ArrayList<>();
		play.add(13);
		play.add(14);
		play.add(15);
		play.add(16);

		calculateAllPlayerJindou(so, play, "1820", (short) 2, 2);
	}

	public void calculateAllPlayerJindou(int score[], List<Integer> player, String roomid, short roundcount, int roomtype) {

		Map<Integer, Integer> winners = new HashMap<Integer, Integer>();// 下标
																		// 和玩家id
		Map<Integer, Integer> losers = new HashMap<Integer, Integer>();
		Map<Integer, Integer> debt = new ConcurrentHashMap<Integer, Integer>();// 玩家id
																				// 和值
		for (int i = 0; i < score.length; i++) {
			if (score[i] > 0) {
				winners.put(i, player.get(i));
			}
			if (score[i] < 0) {
				losers.put(i, player.get(i));
				score[i] = -score[i];
			}
		}

		// 扣钱 及负债计算
		for (Map.Entry<Integer, Integer> entry : losers.entrySet()) {
			int loserPlayerId = entry.getValue();
			PlayingRole pr = SessionManager.getInstance().getPlayer(loserPlayerId);
			PlayerBean pd = null;
			if (pr != null) {
				pd = pr.getPlayerBean();
			} else {
				pd = PlayerDao.getInstance().getPlayerById(loserPlayerId);
			}
			Long curJindou = pd.getJin_dou();
			int reduceJindou = score[entry.getKey()];
			if (curJindou < reduceJindou) {
				debt.put(entry.getValue(), (int) (reduceJindou - curJindou));
				reduceJindou = curJindou.intValue();
			}
			ItemManager.getInstance().reduceItemsAndPush(loserPlayerId, ItemConstants.YUANBAO_ITEM_ID, reduceJindou);
		}
		for (Map.Entry<Integer, Integer> entry : winners.entrySet()) {
			int winnerPlayerId = entry.getValue();
			int winJindou = score[entry.getKey()];
			int winNewVal = debtWinJindouDo(winnerPlayerId, winJindou, debt, roomid, roundcount, roomtype);
			if (winNewVal > 0) {
				ItemManager.getInstance().gainItemsAndPush(winnerPlayerId, ItemConstants.YUANBAO_ITEM_ID, winNewVal);
			}
		}
	}

	private int debtWinJindouDo(int winnerPlayerId, int winJindou, Map<Integer, Integer> debt, String roomid, short roundcount, int roomtype) {
		if (debt.size() <= 0) {
			return winJindou;
		}
		int gainWinJindou = winJindou;
		for (int losePlayerId : debt.keySet()) {
			int loseJindou = debt.get(losePlayerId);
			DabtBean dabtbean = new DabtBean();
			int debtJindou = loseJindou;
			// 赢家的钱全部被欠了
			if (gainWinJindou <= loseJindou) {
				debtJindou = gainWinJindou;
			}
			dabtbean.setPlayerid(losePlayerId);
			dabtbean.setDabt_money(debtJindou);
			dabtbean.setCreditor_id(winnerPlayerId);
			dabtbean.setIs_pay(false);
			DabtdbDao.getInstance().addDabt(dabtbean);
			DabtCache.getInstance().addDabtBean(dabtbean);
			// 发邮件 给输钱的玩家
			sendLoser(winnerPlayerId, losePlayerId, roomid, roomtype, roundcount, debtJindou);
			// 发邮件赢钱
			sendWinmail(losePlayerId, winnerPlayerId, roomid, roomtype, roundcount, debtJindou);

			int newLoseVal = loseJindou - gainWinJindou;
			if (newLoseVal == 0) {
				debt.remove(losePlayerId);
				return 0;
			}
			if (newLoseVal < 0) {
				debt.remove(losePlayerId);
				gainWinJindou = -newLoseVal;
			}
			if (newLoseVal > 0) {
				debt.put(losePlayerId, newLoseVal);
				return 0;
			}
		}
		return gainWinJindou;
	}

	/**
	 * 发给欠钱的玩家
	 */
	public void sendLoser(int winner_id, int loserId, String roomid, int roomtype, short roundcount, int jindou) {
		logger.info("send loser ={},winner={}", loserId, winner_id);
		Map<String, String> params = new HashMap<String, String>();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH点mm分");//
		params.put("$1", dateFormat.format(now));
		params.put("$2", "" + getRoomNameById(roomtype));
		params.put("$3", roomid);
		params.put("$4", "" + roundcount);
		PlayingRole pr = SessionManager.getInstance().getPlayer(winner_id);
		if (pr != null) {
			params.put("$5", pr.getPlayerBean().getName());
		} else {
			PlayerBean pd = PlayerDao.getInstance().getPlayerById(winner_id);
			params.put("$5", pd.getName());
		}
		params.put("$6", "" + jindou);
		MailManager.getInstance().sendMailSigleToPlayer(loserId, MailManager.PLAY_DABT, params, null);
	}

	/**
	 * 发给赢钱的玩家
	 **/
	public void sendWinmail(int loserId, int winnerId, String roomid, int roomtype, short roundcount, int jindou) {
		logger.info("send winner ={},winner={}", winnerId, loserId);
		Map<String, String> params = new HashMap<String, String>();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH点mm分");//
		params.put("$1", dateFormat.format(now));
		params.put("$2", getRoomNameById(roomtype));
		params.put("$3", roomid);
		params.put("$4", "" + roundcount);
		PlayingRole pr = SessionManager.getInstance().getPlayer(loserId);
		if (pr != null) {
			params.put("$5", "" + pr.getPlayerBean().getName());
		} else {
			PlayerBean pd = PlayerDao.getInstance().getPlayerById(loserId);
			params.put("$5", pd.getName());
		}
		params.put("$6", loserId + "");
		params.put("$7", "" + jindou);
		MailManager.getInstance().sendMailSigleToPlayer(winnerId, MailManager.FINANCE_INFORM, params, null);
	}

	private String getRoomNameById(int roomtype) {
		switch (roomtype) {
		case 1:
			return "斗地主";
		case 2:
			return "牛牛";
		case 3:
			return "十三水";
		case 4:
			return "厦门麻将";
		case 5:
			return "泉州麻将";
		}
		return "未知类型房间";

	}

	public static void main(String[] args) {
		// Map<Integer, Integer> losers = new HashMap<Integer, Integer>();
		// losers.put(1, 0);
		// losers.put(2, 3);
		// losers.put(6, 5);
		// for (Map.Entry<Integer, Integer> entry : losers.entrySet()) {
		// if(entry.getValue()==0) {
		// losers.remove(entry.getKey());
		// }
		// }
		// logger.info("==={}",losers);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH点mm分");//
		System.out.println("--" + dateFormat.format(now));
		System.out.println(-0);
	}

}
